package com.edais.service.imp;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.ClickCountDao;
import com.edais.domain.ClickCount;
import com.edais.domain.ClickManyGrab;
import com.edais.service.ClickCountService;
import com.edais.util.Consts;

@Service

@Transactional
public class ClickCountServiceImp implements ClickCountService {

	@Autowired
	private ClickCountDao clickCountDao;
	
	/**
	 * 根据参数取得功能点是否参与统计
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getClickCount(Map<String, String> paramsMap) throws Exception {
		
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		// 根据参数取得功能点是否参与统计
		ClickCount clickCount = this.clickCountDao.getFuncByFuncId(paramsMap);
		if (clickCount == null) {
			rtnMap.put("clickRescode", Consts.CHECK_CODE);
			rtnMap.put("clickResmsg", "功能点为空");
			return rtnMap;
		}

		if (clickCount.getType() != 2) {
			rtnMap.put("clickRescode", Consts.CHECK_CODE);
			rtnMap.put("clickResmsg", "该功能点未开启统计功能！");
			return rtnMap;
		}
		
		String interfaceName = (String)paramsMap.get("interfaceName");
		String mobile = (String)paramsMap.get("mobile");
		String channel = (String)paramsMap.get("channel");
		String funcId = (String)paramsMap.get("funcId");
		if (interfaceName != null && !"null".equals(interfaceName) && !"".equals(interfaceName)) {
			funcId = clickCount.getId().toString();
		} 
		ClickManyGrab clickGrab = new ClickManyGrab();
		clickGrab.setFunc_id(funcId);
		clickGrab.setMobile(mobile);
		clickGrab.setChannel(channel);
		ClickManyGrab clickGrab2 = this.clickCountDao.selClickManyGrab(clickGrab);
		
		// 更新用户点击率
		long l = this.clickCountDao.uptClickManyGrab(clickGrab);
		
		if (l == 0) {
			// 统计用户点击率
			this.clickCountDao.insertClickManyGrab(clickGrab);
		} 
		
		if (clickCount.getIs_limit() == 0) {
			rtnMap.put("clickRescode", Consts.CHECK_CODE);
			rtnMap.put("clickResmsg", "不限制访问次数！");
			return rtnMap;
		}
		
		if (clickGrab2.getClick_count()!= null && clickGrab2.getClick_count() !=0 && clickGrab2.getClick_count() > clickCount.getLimit()) {
			// 提示用户访问超过次数
			rtnMap.put("clickRescode", Consts.SECURITY_CODE);
			rtnMap.put("clickResmsg", "用户访问超过次数！");
			return rtnMap;
		}
		
		rtnMap.put("clickRescode", Consts.SUCCESS_CODE);
		rtnMap.put("clickResmsg", "点击率统计正常终了！");
		return rtnMap;
	}

	public boolean checkClickCount(Map<String, String> paramsMap)
			throws Exception {

		// 根据参数取得功能点是否参与统计
		ClickCount clickCount = clickCountDao.getFuncByFuncId(paramsMap);
		if (clickCount == null) {
			return false;
		}

		if (clickCount.getType() != 2) {
			return false;
		}
		return true;
	}
}
